<?php

namespace App\Common\Tencent\Face;

use App\Service\FaceResultsLogService;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class Face
{
    //WBappid
    protected $appId = "";
    protected $secret = "";
    protected $grantType = "client_credential";
    protected $version = "1.0.0";
    protected $type = "NONCE";
    protected $sourcePhotoType = "1";

    public function __construct()
    {
        $config = Config::get('TencentConfig.face');
        $this->appId = $config['WBappid'];
        $this->secret = $config['Secret'];
    }

    public function setType($type){
        $this->type = $type;
    }

    /**
     * 获取access_token
     * @return mixed
     */
    public function getAccessToken()
    {
        $arr['app_id'] = $this->appId;
        $arr['secret'] = $this->secret;
        $arr['grant_type'] = $this->grantType;
        $arr['version'] = $this->version;
        $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token';

        $key = "";
        foreach ( $arr as $k => $v )
        {
            $key.= "$k=" . urlencode( $v ). "&" ;
        }
        $url = $url."?" .$key;
        $url = substr($url,0,strlen($url)-1);

        $res = postCurl($url,'',[],2);
        Log::info('获取人脸核身getAccessToken'.\GuzzleHttp\json_encode($res,JSON_UNESCAPED_UNICODE));
        return $res;
    }


    /**
     * 获取getTicket
     * @param $access_token
     * @param int $user_sn
     * @param $user_id
     * @return bool|mixed
     */
    public function getTicket($access_token,$user_id)
    {
        $arr['app_id'] = $this->appId;
        $arr['version'] =  $this->version;
        $arr['access_token'] = $access_token;
        $arr['type'] = $this->type;
        if($this->type == "NONCE"){
            $arr['user_id'] = (string)$user_id;
        }
        $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket';

        $key = "";
        foreach ( $arr as $k => $v )
        {
            $key.= "$k=" . urlencode( $v ). "&" ;
        }
        $url = $url."?" .$key;
        $url = substr($url,0,strlen($url)-1);

        $res = postCurl($url,'',[],2);
        Log::info('用户'.$user_id.' - 获取人脸核身getTicket - '.$this->type.json_encode($res, JSON_UNESCAPED_UNICODE));
        return $res;
    }

    /**
     * 获取getFaceId
     * @param $idCard
     * @param $name
     * @param $ticket
     * @param $user_sn
     * @param $user_id
     * @return mixed
     */
    public function getFaceId($idCard ,$name ,$ticket ,$user_id)
    {
        $url = "https://miniprogram-kyc.tencentcloudapi.com/api/server/getfaceid?orderNo=xxx";
        $nonceStr  = getRandom(32);
        $sign_arr = [
            'wbappid'   => $this->appId,
            'userId'    => (string)$user_id,
            'version'   => $this->version,
            'ticket'    => $ticket,
            'nonce'  => $nonceStr
        ];

        $arr_test = array_values($sign_arr);
        asort($arr_test);
        $arr_test = implode('',$arr_test);
        $sign = strtoupper(sha1($arr_test));

        list($t1, $t2) = explode(' ', microtime());
        $orderNo =  date("Ymd").sprintf('%.0f',(floatval($t1)+floatval($t2))*1000) .rand(10000,90000);

        $req_data['webankAppId'] =  $this->appId;
        $req_data['orderNo'] = (string)$orderNo;
        $req_data['name'] = $name;
        $req_data['idNo'] = $idCard;
        $req_data['userId'] = (string)$user_id;
        $req_data['sourcePhotoType'] = $this->sourcePhotoType;
        $req_data['version'] = $this->version;
        $req_data['sign'] = $sign;
        $req_data['nonce'] = $nonceStr;

        $header = array(
            'Content-Type: application/json'
        );
        $url = $url."?orderNo=$orderNo";
        $res = postCurl($url,\GuzzleHttp\json_encode($req_data),$header,1);
        Log::info('用户'.$user_id.' - 获取人脸核身getFaceId'.\GuzzleHttp\json_encode($res));

        unset($res['result']['transactionTime']);
        unset($res['result']['success']);
        $res['result']['sign'] = $sign;
        $res['result']['userId'] = $user_id;
        $res['result']['apiVersion'] = $this->version;
        $res['result']['nonce'] = $nonceStr;
        return $res;
    }

    public function sign($ticket ,$user_id ,$nonceStr)
    {
        $sign_arr = [
            'wbappid'   => $this->appId,
            'userId'    => (string)$user_id,
            'version'   => $this->version,
            'ticket'    => $ticket,
            'nonce'  => $nonceStr
        ];
        $arr_test = array_values($sign_arr);
        asort($arr_test);
        $arr_test = implode('',$arr_test);
        $sign = strtoupper(sha1($arr_test));
        return $sign;
    }

    /**
     * 获取人脸核身返回结果
     * @param $ticket
     * @param $order_no 订单号
     * @param $user_id
     * @param int $get_file 返回 1照片视频，2照片，3视频，其他不返回
     * @return mixed
     */
    public function GetFaceResults($ticket,$order_no,$user_id,$get_file = 0){
        $nonceStr  = getRandom(32);
        $sign_val = [];
        array_push($sign_val,$this->appId,$this->version,$nonceStr,$order_no,$ticket);
        asort($sign_val);
        $sign_val = implode('',$sign_val);
        $sign = strtoupper(sha1($sign_val));

        $arr['app_id'] = $this->appId;
        $arr['version'] =  $this->version;
        $arr['nonce'] = $nonceStr;
        $arr['order_no'] = $order_no;
        $arr['sign'] = $sign;
        $arr['get_file'] = $get_file;

        $url = "https://miniprogram-kyc.tencentcloudapi.com/api/server/sync";
        $key = "";
        foreach ( $arr as $k => $v )
        {
            $key.= "$k=" . urlencode( $v ). "&" ;
        }
        $url = $url."?" .$key;
        $url = substr($url,0,strlen($url)-1);
        $res = postCurl($url,'',[],2);
        Log::info('获取'.$order_no.' - 人脸核身结果 - '.\GuzzleHttp\json_encode($res));

        //保存记录表
        $arr_log['biz_seq_no'] = $res['bizSeqNo'];
        $arr_log['order_no'] = $res['order_no'];
        $arr_log['user_id'] = $user_id;
        $arr_log['data'] = \GuzzleHttp\json_encode($res);

        $face_log_service = new FaceResultsLogService();
        $add_save = $face_log_service->add($arr_log);
        if($add_save['code'] != 200){
            Log::info('获取'.$order_no.' - 信息保存失败 - '.\GuzzleHttp\json_encode($res));
        }
        return $res;
    }



}
